package cn.demos.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
//@EnableTransactionManagement
@ComponentScan("cn.demos.service")
@ImportResource("classpath:spring-mvc.xml")
public class MyBatisConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/demos");
        ds.setUsername("root");
        ds.setPassword("okok");
        return ds;
    }

    @Bean(autowire = Autowire.BY_NAME)
    public SqlSessionFactoryBean sessionFactory() throws Exception{
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

     /*   factory.setMapperLocations(new Resource[]{
                new ClassPathResource("")
        });*/
        factory.setTypeAliasesPackage("cn.demos.pojo");
        return  factory;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer conf = new MapperScannerConfigurer();
        conf.setBasePackage("cn.demos.dao");
        conf.setSqlSessionFactoryBeanName("sessionFactory");
        return conf;

    }
}
